package io.gitee.tuo_tuo.jfinaldevassistance.test;

import com.google.common.base.Joiner;
import com.google.common.base.Throwables;
import com.google.common.io.Files;
import io.gitee.tuo_tuo.jfinaldevassistance.common.Rst;
import io.gitee.tuo_tuo.jfinaldevassistance.util.Reflect;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;

/**
 * 描述:
 * 版权: Copyright (c) 2018
 * 作者: tuotuo
 * 版本: 1.0
 * 创建日期: 2018/8/7
 * 创建时间: 9:29
 */
public class HttpClient {
	protected MockHttpRequest request = new MockHttpRequest();
	protected MockHttpResponse response;
	private String actionUrl;
	private File responseFile;

	public static HttpClient instance(){
		return new HttpClient();
	}

	public String invoke() {
		StringWriter stringWriter = new StringWriter();
		response = new MockHttpResponse(stringWriter);
		Reflect.on(JFinalTestSupport.handler).call("handle", getTarget(actionUrl, request), request, response, new boolean[] { true });
		String result = stringWriter.toString();
		if (responseFile != null) {
			try {
				Files.write(result, responseFile, Charset.forName("UTF-8"));
			} catch (IOException e) {
				Throwables.propagate(e);
			}
		}
		return result;
	}

	public Rst invokeForRst(){
		String result = invoke();
		return Rst.parse(result);
	}

	private String getTarget(String url, MockHttpRequest request) {
		if(url == null){
			throw new RuntimeException("url 为空！");
		}
		String target = url;
		if (url.contains("?")) {
			target = url.substring(0, url.indexOf("?"));
			String queryString = url.substring(url.indexOf("?") + 1);
			String[] keyVals = queryString.split("&");
			for (String keyVal : keyVals) {
				int i = keyVal.indexOf('=');
				String key = keyVal.substring(0, i);
				String val = keyVal.substring(i + 1);
				request.setParameter(key, val);
			}
		}
		return target;
	}

	public HttpClient addParams(Map<String, Object> map){
		map.forEach((key, value) ->{
			addParam(key, value);
		});
		return this;
	}

	public HttpClient addParam(String key, Object value){
		request.setParameter(key, value.toString());
		return this;
	}

	public HttpClient addBody(File bodyFile) {
		String bodyData = "";
		if (bodyFile != null) {
			List<String> req = null;
			try {
				req = Files.readLines(bodyFile, Charset.forName("UTF-8"));
			} catch (IOException e) {
				Throwables.propagate(e);
			}
			bodyData = Joiner.on("").join(req);
		}
		request.setBody(bodyData);
		return this;
	}

	public HttpClient addBody(String bodyData) {
		request.setBody(bodyData);
		return this;
	}

	public HttpClient use(String actionUrl) {
		this.actionUrl = actionUrl;
		return this;
	}

	public HttpClient writeTo(File responseFile) {
		this.responseFile = responseFile;
		return this;
	}

	public Object findAttrAfterInvoke(String key) {
		return request.getAttribute(key);
	}
}
